package system.student.funtion.exhibition;

import system.student.entity.*;
import system.student.entity.Dept;

import system.student.entity.Clazz;
import system.student.entity.StudentDetail;
import system.student.entity.logInfo.SystemLog;
import system.student.entity.login.LoginResponse;
import system.student.entity.user.Teacher;
import system.student.entity.user.UserInfo;
import system.student.funtion.exhibition.adminfunction.DeptService;
import system.student.funtion.exhibition.adminfunction.TeacherService;
import system.student.funtion.exhibition.adminfunction.TrainingPlanService;
import system.student.funtion.exhibition.adminfunction.impl.DeptServiceImpl;
import system.student.funtion.exhibition.adminfunction.ClazzService;
import system.student.funtion.exhibition.adminfunction.impl.ClazzServiceImpl;
import system.student.funtion.exhibition.adminfunction.impl.TeacherServiceImpl;
import system.student.funtion.exhibition.adminfunction.impl.trainingPlanServiceImpl;
import system.student.mapper.ClazzMapper;
import system.student.mapper.LogMapper;
import system.student.mapper.StudentMapper;
import system.student.util.MapperUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class AdminExhibition {
    private static final Scanner scanner = new Scanner(System.in);
    private static final TeacherService teacherService = new TeacherServiceImpl();
    private static final DeptService deptService = new DeptServiceImpl();
    private static final StudentMapper studentMapper = MapperUtil.getMapper(StudentMapper.class);
    private static final TrainingPlanService trainingPlanService = new trainingPlanServiceImpl();
    private static final LogMapper logMapper = MapperUtil.getMapper(LogMapper.class);

    public static void runningAdminExhibition(LoginResponse loginResponse) {
        UserInfo user = (UserInfo) loginResponse.getUser();
        boolean flag = true;
        while (flag) {
            System.out.println(user.getUsername() + "欢迎回来, 管理员先生");
            System.out.println("1.学生信息管理");
            System.out.println("2.教师信息管理");
            System.out.println("3.班级信息管理");
            System.out.println("4.部门信息管理");
            System.out.println("5.培训计划管理");
            System.out.println("6.查询日志");
            System.out.println("7.退出登录");
            String option = scanner.nextLine();
            switch (option) {
                case "1": {
                    System.out.println("学生信息管理");
                    studentManage();
                }
                ;
                break;
                case "2": {
                    teacherManage();
                }
                ;
                break;
                case "3": {
                    classManage();
                }
                ;
                break;
                case "4": {
                    deptManage();
                }
                ;
                break;
                case "5": {
                    trainingPlanManage();
                }
                ;
                break;
                case "6": {
                    System.out.println("查询日志");
                    List<SystemLog> systemLogs =logMapper.printLog();
                    for (int i = 0; i < systemLogs.size(); i++) {
                        System.out.println("操作人:"+systemLogs.get(i).getOperatorName()+"(ID"+systemLogs.get(i).getOperatorId()+"):于"
                                +systemLogs.get(i).getLogTime()+"进行了"+systemLogs.get(i).getOperatorType());
                    }
                }
                case "7": {
                    flag = false;
                    System.out.println("退出成功");
                }
                ;
                break;
                default: {
                    System.out.println("功能未发放");
                }
                ;
                break;
            }
        }

    }

    private static void deptManage() {
        while (true) {
            System.out.println("请选择操作");
            System.out.println("1.创建部门");
            System.out.println("2.修改部门");
            System.out.println("3.删除部门");
            System.out.println("4.查询所有部门");
            System.out.println("5.退出");
            String option = scanner.nextLine();
            switch (option){
                case "1":{
                    System.out.println("请输入部门名称");
                    String deptName = scanner.nextLine();
                    Dept dept = new Dept(null,deptName);
                    deptService.addDept(dept);
                }
                break;
                case "2":{
                    System.out.println("目前所有部门");
                    List<Dept> depts = deptService.findAllDept();
                    if (!depts.isEmpty()) {
                        // 打印表头
                        System.out.println("+-----+--------------------+");
                        System.out.printf("| %-5s | %-20s |%n", "ID", "Department Name");
                        System.out.println("+-----+--------------------+");
                        // 打印每一行数据
                        for (Dept dept : depts) {
                            System.out.println(dept.toString());
                        }
                        // 打印表尾
                        System.out.println("+-----+--------------------+");
                    } else {
                        System.out.println("暂无部门信息");
                    }
                    System.out.println("请输入你要修改的部门的id");
                    Long id = scanner.nextLong();
                    scanner.nextLine();
                    System.out.println("请输入你要修改的部门的名称");
                    String department = scanner.nextLine();
                    Dept dept = new Dept(id, department);
                    deptService.updateDept(dept);
                }
                break;
                case "3": {
                    System.out.println("删除部门");
                    System.out.println("目前所有部门");
                    List<Dept> depts = deptService.findAllDept();
                    if (!depts.isEmpty()) {
                        // 打印表头
                        System.out.println("+-----+--------------------+");
                        System.out.printf("| %-5s | %-20s |%n", "ID", "Department Name");
                        System.out.println("+-----+--------------------+");
                        // 打印每一行数据
                        for (Dept dept : depts) {
                            System.out.println(dept.toString());
                        }
                        // 打印表尾
                        System.out.println("+-----+--------------------+");
                    } else {
                        System.out.println("暂无部门信息");
                    }
                    System.out.println("请输入你要删除的部门的id");
                    Long depId = scanner.nextLong();
                    scanner.nextLine();
                    List<Teacher> teachers = deptService.findAllTeacherById(depId);
                    if (!teachers.isEmpty()){
                        System.out.println("该部门下有老师,是否强制删除,删除后老师的部门将为空,若强制删除请按:y");
                        String choice = scanner.nextLine();
                        if ("y".equals(choice)){
                            deptService.updateTeacherDepartment(depId);
                            deptService.deleteDept(depId);
                            System.out.println("删除成功");
                        }
                    }else {
                        deptService.deleteDept(depId);
                        System.out.println("删除成功");
                    }
                }
                break;
                case "4":{
                    System.out.println("查询所有部门");
                    List<Dept> depts = deptService.findAllDept();
                    if (!depts.isEmpty()) {
                        // 打印表头
                        System.out.println("+-----+--------------------+");
                        System.out.printf("| %-5s | %-20s |%n", "ID", "Department Name");
                        System.out.println("+-----+--------------------+");
                        // 打印每一行数据
                        for (Dept dept : depts) {
                            System.out.println(dept.toString());
                        }
                        // 打印表尾
                        System.out.println("+-----+--------------------+");
                    } else {
                        System.out.println("暂无部门信息");
                    }
                }
                break;
                case "5": return;
                default:{
                    System.out.println("输入错误");
                }
                break;
            }
        }
    }

    private static void classManage() {
        while (true) {
            System.out.println("请选择操作");
            System.out.println("1.创建班级");
            System.out.println("2.修改班级");
            System.out.println("3.删除班级");
            System.out.println("4.查询所有班级");
            System.out.println("5.退出");
            String option = scanner.nextLine();
            ClazzService clazzService = new ClazzServiceImpl();
            switch (option) {
                case "1": {
                    System.out.println("请输入班级名称");
                    String classname = scanner.nextLine();
                    System.out.println("请输入老师id");
                    Long teacherId = Long.parseLong(scanner.nextLine());
                    clazzService.addClazz(classname, teacherId);
                }
                ;
                break;
                case "2": {
                    System.out.println("请输入班级id");
                    Long classId = Long.parseLong(scanner.nextLine());
                    System.out.println("请输入班级名称");
                    String classname = scanner.nextLine();
                    System.out.println("请输入老师id");
                    Long teacherId = Long.parseLong(scanner.nextLine());
                    clazzService.changeClazz(classId, classname, teacherId);

                }
                ;
                break;
                case "3": {
                    System.out.println("请输入班级名称");
                    String classname = scanner.nextLine();
                    clazzService.deleteClazz(classname);
                    System.out.println("删除成功");
                }
                break;
                case "4": {
                    ClazzMapper clazzMapper = MapperUtil.getMapper(ClazzMapper.class);
                    List<Clazz> clazzes = clazzService.selectAllClazz();
                    List<String> teacherNames = new ArrayList<>();
                    clazzes.forEach(clazz -> clazz.setTeacherName(clazzMapper.selectByTeacherId(clazz.getTeacherId())));
                    // 输出表头（调整列宽和对齐）
                    System.out.printf("%-5s %-20s %-10s %-15s%n", "ID", "班级名称", "老师ID", "老师名称");
                    System.out.println("------------------------------------------------------");
                    // 格式化输出每个班级的信息
                    clazzes.forEach(clazz -> {
                        // 获取老师名称，处理null值
                        String teacherName = clazz.getTeacherName() != null ? clazz.getTeacherName() : "无";
                        System.out.printf("%-5d %-20s %-10d %-15s%n",
                                clazz.getId(),
                                clazz.getClassname(),
                                clazz.getTeacherId(),
                                teacherName);
                    });
                }
                break;
                case "5": {
                    return;
                }
                default: {
                    System.out.println("请输入正确的选项");
                }
                break;
            }
        }
    }

    private static void teacherManage() {
        while (true) {
            System.out.println("请选择操作");
            System.out.println("1.查询所有老师");
            System.out.println("2.修改老师状态");
            System.out.println("3.分配班级");
            System.out.println("4.分配部门");
            System.out.println("5.退出操作");
            String option = scanner.nextLine();
            switch (option){
                case "1":{
                    List<Teacher> allTeacher = teacherService.selectAllTeacher();
                    System.out.println("+----+----------+------------+---------+");
                    System.out.println("| ID |   Name   | Department | User ID |");
                    System.out.println("+----+----------+------------+---------+");
                    for (Teacher teacher : allTeacher) {
                        System.out.printf("| %-2d | %-8s | %-10s | %-6d |\n",
                                teacher.getId(),
                                teacher.getName(),
                                teacher.getDepartment(),
                                teacher.getUserId());
                    }
                    System.out.println("+----+----------+------------+---------+");
                }break;
                case "2":{
                    while  (true){
                        System.out.println("请输入目标老师的用户id：");
                        Long userId = scanner.nextLong();
                        List<Long> idList = teacherService.selectAllTeacherUserId();
                        if (idList.contains(userId)) {
                            Integer state = teacherService.selectStateByUserId(userId);
                            System.out.println("找到该用户，状态为: " + state);
                            System.out.println("(“1”为启用，“0”为禁用)");
                            while (true) {
                                System.out.println("请输入用户状态:");
                                Integer newState = scanner.nextInt();
                                if (newState != 0 && newState != 1) {
                                    System.out.println("输入有误，请重新输入");
                                    continue;
                                }
                                teacherService.updateStateByUserId(newState, userId);
                                System.out.println("修改成功！");
                                break;
                            }
                            break;
                        } else {
                            System.out.println("未找到该用户，请重新输入！");
                            System.out.println("是否退出操作（“0退出”，“1继续”）");
                            int choice = scanner.nextInt();
                            if(choice == 0){
                                break;
                            }
                        }
                    }
                };break;
                case "3": {
                    System.out.println("所以教师信息如下:");
                    List<Teacher> teacherDetail = teacherService.selectAllTeacherId();
                    System.out.println("+----+----------+");
                    System.out.println("| ID |   Name   |");
                    System.out.println("+----+----------+");
                    List<Long> teacherIdList = new ArrayList<>();
                    for (Teacher  teacher : teacherDetail) {
                        Long id = teacher.getId();
                        teacherIdList.add(id);
                        String name = teacher.getName();
                        System.out.printf("| %-2d | %-8s |\n", id, name);
                    }
                    System.out.println("+----+----------+");
                    System.out.println("班级信息如下:");
                    List<Clazz> classDetail = teacherService.selectAllClassId();
                    System.out.println("+----+----------+");
                    System.out.println("| ID |   Name   |");
                    System.out.println("+----+----------+");
                    List<Long> classIdList = new ArrayList<>();
                    for (Clazz clazz : classDetail) {
                        Long id = clazz.getId();
                        classIdList.add(id);
                        String name = clazz.getClassname();
                        System.out.printf("| %-2d | %-8s |\n", id, name);
                    }
                    System.out.println("+----+----------+");
                    while (true) {
                        System.out.println("请输入教师id");
                        Long teacherId = scanner.nextLong();
                        if(teacherIdList.contains(teacherId)){
                            System.out.println("请输入班级id");
                            Long classId = scanner.nextLong();
                            if(classIdList.contains(classId)){
                                teacherService.insertTeacherIntoClass(teacherId,  classId);
                                System.out.println("分配成功！");
                                break;
                            }else{
                                System.out.println("班级id不正确");
                                System.out.println("退出请输入“0” 继续请输入“1”" );
                                String choice = scanner.nextLine();
                                if(choice.equals("0")){
                                    break;
                                }
                            }
                        }else{
                            System.out.println("教师id不正确");
                            System.out.println("退出请输入“0” 继续请输入“1”" );
                            String choice = scanner.nextLine();
                            if(choice.equals("0")){
                                break;
                            }
                        }
                    }


                };break;
                case "4": {
                    System.out.println("所以教师信息如下:");
                    List<Teacher> teacherDetail = teacherService.selectAllTeacherId();
                    System.out.println("+----+----------+");
                    System.out.println("| ID |   Name   |");
                    System.out.println("+----+----------+");
                    List<Long> teacherIdList = new ArrayList<>();
                    for (Teacher  teacher : teacherDetail) {
                        Long id = teacher.getId();
                        teacherIdList.add(id);
                        String name = teacher.getName();
                        System.out.printf("| %-2d | %-8s |\n", id, name);
                    }
                    System.out.println("+----+----------+");

                    System.out.println("所以部门信息如下:");
                    List<Dept> deptDetail = teacherService.selectAllDeptId();
                    System.out.println("+----+----------+");
                    System.out.println("| ID |   Name   |");
                    System.out.println("+----+----------+");
                    List<Long> deptIdList = new ArrayList<>();
                    for (Dept dept : deptDetail) {
                        deptIdList.add(dept.getId());
                        System.out.printf("| %-2d| %-8s|\n", dept.getId(), dept.getDepartment());
                    }
                    System.out.println("+----+----------+");
                    while (true) {
                        System.out.println("请输入教师id");
                        Long teacherId = scanner.nextLong();
                        if(teacherIdList.contains(teacherId)){
                            System.out.println("请输入部门id");
                            Long deptId = scanner.nextLong();
                            if(deptIdList.contains(deptId)){
                                String deptName = teacherService.selectById(deptId);
                                teacherService.insertTeacherIntoDept(teacherId,  deptId,  deptName);
                                System.out.println("分配成功！");
                                break;
                            }else{
                                System.out.println("部门id不正确");
                                System.out.println("退出请输入“0” 继续请输入“1”" );
                                String choice = scanner.nextLine();
                                if(choice.equals("0")){
                                    break;
                                }
                            }
                        }else{
                            System.out.println("教师id不正确");
                            System.out.println("退出请输入“0” 继续请输入“1”" );
                            String choice = scanner.nextLine();
                            if(choice.equals("0")){
                                break;
                            }
                        }
                    }
                };break;
                case "5": return;
                default:{};break;
            }
        }
    }

    private static void studentManage() {
        while (true) {
            StudentMapper studentMapper = MapperUtil.getMapper(StudentMapper.class);
            System.out.println("请选择操作");
            System.out.println("1.查询所有学生");
            System.out.println("2.修改学生状态");
            System.out.println("3.分配班级");
            System.out.println("4.退出操作");
            String option = scanner.nextLine();
            switch (option) {
                case "1": {
                    List<StudentDetail> studentDetailList = studentMapper.selectStudents();
                    if (studentDetailList.isEmpty()) {
                        System.out.println("暂无学生");
                    }
                    studentDetailList.forEach(System.out::println);
                }
                ;
                break;
                case "2": {
                    System.out.println("请输入学生id");
                    Long studentId = scanner.nextLong();
                    scanner.nextLine();
                    System.out.println("1.启用账号");
                    System.out.println("2.禁用账号");
                    String num = scanner.nextLine();
                    if (num.equals("1")) {
                        studentMapper.updateUseStateById(studentId, 1);
                        System.out.println("启用成功");
                    } else if (num.equals("2")) {
                        studentMapper.updateUseStateById(studentId, 0);
                        System.out.println("禁用成功");
                    } else {
                        System.out.println("功能正在开发中");
                    }
                }
                ;
                break;
                case "3": {
                    System.out.println("请输入学生id");
                    Long studentId = scanner.nextLong();
                    scanner.nextLine();
                    System.out.println("请输入班级id");
                    Long classId = scanner.nextLong();
                    scanner.nextLine();
                    studentMapper.updateClassIdById(studentId, classId);
                    System.out.println("成功加入班级");
                }
                ;
                break;
                case "4":
                    return;
                default: {
                }
                ;
                break;
            }
        }
    }

    private static void trainingPlanManage() {
        while (true) {
            System.out.println("请选择操作");
            System.out.println("1.添加训练计划");
            System.out.println("2.删除训练计划");
            System.out.println("3.查看所有训练计划");
            System.out.println("4.添加培训预算");
            System.out.println("5.查看培训预算");
            System.out.println("6.删除培训预算");
            System.out.println("7.退出操作");
            String option = scanner.nextLine();
            switch (option) {
                case "1": {
                    System.out.println("添加训练计划");
                    TrainingPlan trainingPlan = new TrainingPlan();
                    System.out.println("请输入训练计划");
                    String planName = scanner.nextLine();
                    trainingPlan.setTrainingPlan(planName);
                    System.out.println("当前所有部门");
                    List<Dept> depts = deptService.findAllDept();
                    if (!depts.isEmpty()) {
                        // 打印表头
                        System.out.println("+-----+--------------------+");
                        System.out.printf("| %-5s | %-20s |%n", "ID", "Department Name");
                        System.out.println("+-----+--------------------+");
                        // 打印每一行数据
                        for (Dept dept : depts) {
                            System.out.println(dept.toString());
                        }
                        // 打印表尾
                        System.out.println("+-----+--------------------+");
                    } else {
                        System.out.println("暂无部门信息");
                    }
                    System.out.println("请输入部门id");
                    Long depId = scanner.nextLong();
                    scanner.nextLine();
                    trainingPlan.setDeptId(depId);
                    System.out.println("请输入部门名称");
                    String department = scanner.nextLine();
                    trainingPlan.setDeptName(department);
                    trainingPlanService.addTrainingPlan(trainingPlan);
                }
                break;
                case "2": {
                    System.out.println("当前拥有的训练计划");
                    List<TrainingPlan> trainingPlans = trainingPlanService.findAllTrainingPlan();
                    if(trainingPlans.isEmpty()){
                        System.out.println("当前没有训练计划");
                        break;
                    }else{
                        printTrainingPlans(trainingPlans);
                        System.out.println("请输入删除的训练计划id");
                        Long trainingPlanId = scanner.nextLong();
                        scanner.nextLine();
                        trainingPlanService.deleteTrainingPlan(trainingPlanId);
                    }
                }
                break;
                case "3": {
                    System.out.println("查看所有计划");
                    List<TrainingPlan> trainingPlans = trainingPlanService.findAllTrainingPlan();
                    printTrainingPlans(trainingPlans);
                }
                break;
                case "4":{
                    System.out.println("添加培训预算");
                    List<TrainingPlan> trainingPlans = trainingPlanService.findAllTrainingPlan();
                    if (trainingPlans.isEmpty()){
                        System.out.println("没有培养计划,请先添加训练计划");
                        break;
                    }else {
                        System.out.println("当前拥有的训练计划");
                        printTrainingPlans(trainingPlans);
                        TrainingBudget trainingBudget = new TrainingBudget();
                        System.out.println("请输入要添加预算的培训计划id");
                        trainingBudget.setPlanId(scanner.nextLong());
                        scanner.nextLine();
                        System.out.println("请输入预算类别");
                        trainingBudget.setBudgetCategory(scanner.nextLine());
                        System.out.println("请输入预算金额");
                        trainingBudget.setMoney(scanner.nextLong());
                        scanner.nextLine();
                        trainingPlanService.addTrainingBudget(trainingBudget);
                    }
                }
                break;
                case "5":{
                    System.out.println("当前所有培训预算");
                    List<TrainingBudget> trainingBudgets = trainingPlanService.findAllTrainingBudget();
                    printTrainingBudgetTable(trainingBudgets);
                }
                break;
                case "6":{
                    System.out.println("当前所有培训预算");
                    List<TrainingBudget> trainingBudgets = trainingPlanService.findAllTrainingBudget();
                    if (trainingBudgets.isEmpty()) {
                        System.out.println("当前没有培训预算");
                    }else {
                        printTrainingBudgetTable(trainingBudgets);
                        System.out.println("请输入要删除的培训计划ID");
                        long planId = scanner.nextLong();
                        scanner.nextLine();
                        trainingPlanService.deleteTrainingBudget(planId);
                    }
                }
                break;
                case "7": {
                    return;
                }
                default: {
                    System.out.println("请输入正确的选项");
                }
                break;
            }
        }
    }


    /**
     * 格式化打印培训计划列表
     *
     * @param planList 培训计划列表
     */
    public static void printTrainingPlans(List<TrainingPlan> planList) {
        if (planList == null || planList.isEmpty()) {
            System.out.println("暂无培训计划信息");
            return;
        }
        // 打印表头
        System.out.println("+-----+------------------------------+----------+----------------+------------+");
        System.out.printf("| %-5s | %-25s | %-10s | %-15s | %-10s |%n",
                "ID", "plan Name", "Dept ID", "Dept Name", "Status");
        System.out.println("+-----+------------------------------+----------+----------------+------------+");
        // 打印每一行数据
        for (TrainingPlan plan : planList) {
            System.out.println(plan.toString());
        }
        // 打印表尾
        System.out.println("+-----+------------------------------+----------+----------------+------------+");
    }


    /**
     * 打印预算表
     * @param budgets
     */
    public static void printTrainingBudgetTable(List<TrainingBudget> budgets) {
        if (budgets == null || budgets.isEmpty()) {
            System.out.println("暂无培训预算信息");
            return;
        }
        // 打印表头
        System.out.println("+-------+------------+----------------------+------------+");
        System.out.printf("| %-5s | %-10s | %-20s | %-10s |%n",
                "ID", "Plan ID", "Budget Category", "Money");
        System.out.println("+-------+------------+----------------------+------------+");
        // 打印每一行数据
        for (TrainingBudget budget : budgets) {
            System.out.println(budget.toString());
        }
        // 打印表尾
        System.out.println("+-------+------------+----------------------+------------+");
    }

}
